﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlueLotus7.Eden.Service;
using BlueLotus7.Web;
using BlueLotus7.ArchiveSystem.Common;
using BlueLotus7.Eden.KB.Status.Models;

namespace BlueLotus7.Eden.Web.Areas.KB.Controllers
{
    public class StatusController : BaseController
    {
        protected const string Column_StatusMark = "col-status-mark";

        //
        // GET: /KB/Status/

        #region Pages

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List()
        {
            ArchiveStatusService service = new ArchiveStatusService();

            var scopeKey = new Guid("04B32D12-BCBC-4467-9B66-1C65EA90E71E");
            var users = service.QueryDomainScopeUsers(scopeKey, null);
            Dictionary<string, StatusGridControlModel> model = new Dictionary<string, StatusGridControlModel>();
            foreach (var one in users)
            {
                StatusGridControlModel m = new StatusGridControlModel();
                m.DomainScopeKey = one.DomainScope.Key;
                m.DomainScopeUserKey = one.Key;
                m.EnumType = typeof(QQStatus);
                m.Mergable = false;
                m.TargetStatusList.AddRange(service.QueryStatus(scopeKey, one.Key, null, null));
                model.Add(one.ThirdPartyIdentity + (string.IsNullOrWhiteSpace(one.Description) ? string.Empty : "(" + one.Description + ")"), m);
            }

            return View(model);
        }

        /// <summary>
        /// Page for Query
        /// </summary>
        /// <returns></returns>
        public ActionResult Query()
        {
            StatusQueryPageModel model = new StatusQueryPageModel();
            ArchiveStatusService service = new ArchiveStatusService();
            var domainScopes = service.QueryDomainScopeList(null, null);

            model.DomainScopes.AddRange(domainScopes);
            return View(model);
        }

        public ActionResult Users()
        {
            //       DomainScopeUserListPageModel model = new DomainScopeUserListPageModel();
            return View();
        }

        public ActionResult StatusView(Guid key)
        {
            ArchiveStatusService service = new ArchiveStatusService();
            var users = service.QueryDomainScopeUsers(key, null);
            return PartialView("DomainScopeUserListView", users);
        }

        #endregion

        #region Ajax Handlers

        public JsonResult GetUserListByDomainScopeKey(Guid key)
        {
            AjaxResult result = new AjaxResult();

            try
            {
                ArchiveStatusService service = new ArchiveStatusService();
                var users = service.QueryDomainScopeUsers(key, null);
                GridSource source = new GridSource("domainScopeUsers");
                foreach (var one in users)
                {
                    source.Items.Add(new KeyValuePair<string, string>(one.Key.ToString(), one.Description));
                }

                result.Data = source;
                result.IsSuccess = true;
            }
            catch (Exception ex)
            {

            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Query status grid by criterias
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public PartialViewResult QueryStatusGridByCriterias(QueryStatusByCriteriasRequest request)
        {
            AjaxResult result = new AjaxResult();
            StatusGridControlModel model = new StatusGridControlModel();

            try
            {
                ArchiveStatusService service = new ArchiveStatusService();
                DomainScope domainScope = service.GetDomainScopeByKey(request.DomainScopeKey);

                if (domainScope != null)
                {
                    model.TargetStatusList.AddRange(service.QueryStatus(request.DomainScopeKey, request.DomainScopeUserKey, request.StartStamp, request.EndStamp));
                    model.EnumType = Helper.GetStatusEnumTypeByCode(domainScope.Code);
                    model.Mergable = true;
                }
            }
            catch (Exception ex)
            {

            }
            return PartialView("ControlView/StatusGridControlView", model);
        }

        //public PartialViewResult QueryStatusCalendarByCriterias(QueryStatusByCriteriasRequest request)
        //{
        //    AjaxResult result = new AjaxResult();

        //    try
        //    {
        //        ArchiveStatusService service = new ArchiveStatusService();
        //        List<TargetStatus> records = service.QueryStatus(request.DomainScopeKey, request.DomainScopeUserKey, request.StartStamp, request.EndStamp);

        //        result.Data = ConvertTargetStatusToGridData(records);
        //        result.IsSuccess = true;
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //    return Json(result);
        //}

        public JsonResult MergeStatus(MergeStatusRequest request)
        {
            AjaxResult result = new AjaxResult();

            if (!Validator.IsZeroGuid(request.DomainScopeUserKey) && request.Status >= 0 && !Validator.IsZeroGuid(request.StartGuid) && !Validator.IsZeroGuid(request.EndGuid))
            {
                ArchiveStatusService service = new ArchiveStatusService();
                service.MergeStatus(request.DomainScopeUserKey, request.Status, request.StartGuid, request.EndGuid);
                result.IsSuccess = true;
            }
            else
            {
                result.ErrorMessage = "Invalid parameters.";
            }

            return Json(result);
        }

        #endregion

        #region Converts

        protected GridData ConvertTargetStatusToGridData(Type statusEnumType, List<TargetStatus> records)
        {
            GridData gridData = new GridData();
            gridData.Columns = new List<GridColumn>();

            //From
            GridColumn columnFrom = new GridColumn();
            columnFrom.CSS = Column_Stamp;
            columnFrom.Type = DataType.Text;
            columnFrom.Name = "StartStamp";
            columnFrom.Title = "Start From";
            gridData.Columns.Add(columnFrom);

            //To
            GridColumn columnTo = new GridColumn();
            columnTo.CSS = Column_Stamp;
            columnTo.Type = DataType.Text;
            columnTo.Name = "EndStamp";
            columnTo.Title = "End To";
            gridData.Columns.Add(columnTo);

            //Status
            GridColumn columnStatus = new GridColumn();
            columnStatus.CSS = Column_Status;
            columnStatus.Type = DataType.Text;
            columnStatus.Title = columnStatus.Name = "Status";
            gridData.Columns.Add(columnStatus);

            //Status-mark
            GridColumn columnStatusMark = new GridColumn();
            columnStatusMark.CSS = Column_StatusMark;
            columnStatusMark.Type = DataType.Text;
            columnStatusMark.Title = columnStatusMark.Name = string.Empty;
            gridData.Columns.Add(columnStatusMark);

            GridRow row = null;

            if (records != null && records.Count > 0)
            {
                foreach (var one in records)
                {
                    row = new GridRow();
                    row.ID = one.Key.ToString();
                    GridCell cell;

                    cell = new GridCell();
                    cell.Column = columnFrom.Name;
                    cell.Value = cell.Text = Helper.ConvertToDisplayString(one.StartStamp);
                    row.Cells.Add(cell);

                    cell = new GridCell();
                    cell.Column = columnTo.Name;
                    cell.Value = cell.Text = Helper.ConvertToDisplayString(one.EndStamp);
                    row.Cells.Add(cell);

                    cell = new GridCell();
                    cell.Column = columnStatus.Name;
                    var statusValue = cell.Value = cell.Text = Enum.ToObject(statusEnumType, one.Status).ToString();
                    row.Cells.Add(cell);

                    cell = new GridCell();
                    cell.Column = columnStatusMark.Name;
                    cell.Value = cell.Text = string.Empty;
                    cell.CSS = statusValue.ToLowerInvariant();
                    row.Cells.Add(cell);

                    gridData.Rows.Add(row);
                }
            }

            return gridData;
        }

        #endregion

        protected Type GetStatusEnumTypeByCode(string code)
        {
            Type result = typeof(int);

            if (!string.IsNullOrWhiteSpace(code))
            {
                switch (code.ToLowerInvariant())
                {
                    case "qq":
                        result = typeof(QQStatus);
                        break;
                    default:
                        break;
                }
            }

            return result;
        }
    }
}
